/**
 * 单据
 */
import { mapState } from "vuex";
import { pageList } from "@/api/inventory/unit";//计量单位

import { list as listDesign } from "@/api/erp/voucherDesign";//动态表单

import { IdFieldToNameField } from "@/utils/customize"

import { getbyid } from '@/api/purchase/voucherDesign';

import { handleDynamicData } from "@/utils/tool/dynamic-data"

import { drawerBox } from "@/components/PopUpLayer";//搜索选择弹窗

import getDate from "@/utils/tool/date";

import EditableCell from "@/components/OrderDynamicForm/EditableCell";
import OrderDynamicForm from '@/components/OrderDynamicForm/OrderDynamicForm';
import dynamicList from '@/components/OrderDynamicForm/dynamicList';
import dynamicListDetails from '@/components/OrderDynamicForm/dynamicListDetails'
import btnsWrapper from '@/components/OrderDynamicForm/btnsWrapper'

import { Controlwidth } from "@/utils/antTableComponents";

export default {
    components: {
        EditableCell,
        OrderDynamicForm,   //动态表单
        drawerBox,          //抽屉搜索列表
        dynamicList,        //表单列表
        dynamicListDetails, //明细列表
        btnsWrapper,        //顶部按钮
    },
    updated () {
        Controlwidth("bills_tb", 50);
    },
    data () {
        return {
            //----------↓样式----------
            btn_grid: {
                xs: 2,
                sm: 2,
                md: 2,
                lg: 2,
                xl: 2
            },
            formLayout: "inline",
            labelCol: { span: 8 },
            wrapperCol: { span: 16 },
            //----------↑样式----------

            unitData: [],           //单计量数组
            unitsDataDetails: [],   //多计量数组详细计量

            form: "",
            dynamicFormData: [],
            columns: [],            //明细table的cloums
            dataSource: [],         //明细table的数据
            dataSourceNumber: 8,    //明细table初始多少条
            count: 0,               //明细table列表行条数
            slotArray: [],          //明细中 需要编辑的字段

            orderHeaderData: [],    //表头动态表单名
            orderFooterData: [],    //表尾动态表单名
            orderDetailData: [],    //明细动态表单名
            orderDetailBomData: [], //物料明细

            receiptNumber: 0,       //单据编号

            visible: false,         //控制右键菜单显示
            top: 0,
            left: 0,
            customClick: (record, index) => ({
                on: {
                    contextmenu: (e) => {//右键事件
                        e.preventDefault();
                        if (record.number != "合计") {
                            this.openMenu(e);
                            console.log('右键点击的', index);
                            this.thisClickId = index;
                            this.thisClickRecord = record;
                        }
                    },
                    click: () => {
                        this.classWorkCurrent = record.id;//加工单当前点击的行数

                        //单据保存后 再次获取物料明细

                        // if (record.bomId) {
                        //     this.showDetailsBom(record);
                        // } else {
                        //     this.dataSourceBom = [];
                        // }

                        // if (record.processRouteId) {
                        //     this.showDetailsRoute(record);
                        // } else {
                        //     this.dataSourceRoute = [];
                        // }

                    }
                },
            }),
            classWorkCurrent: 0,    //加工单当前点击的行数
            thisClickId: 0,         //当前右键点击的行的key
            thisClickRecord: {},    //当前右键点击的行的数据

            isRouterAlive: true,

            editData: [],            //修改数据
            orderId: '',              //当前单据id

            unitsAssistSelect: [],   //辅助计量下来数组
            onFillData: [],           //必填字段集合

            editMask: true,     //修改遮罩
            isSaveRun: true,    //保存防连点
            loading: false,     //加载中遮罩层
            voucherState: 0,     //当前单据审核状态


            sourceVoucherData: {},   //数据来源
            sourceVoucherDetails: [], //明细中添加数据来源id
            businessType: null,           //业务类型

            showModel: 'order',      //订单显示模式
            stylePrint: '<style type="text/css" media="print">\n' + '  @page { size: landscape;}\n' + '</style>',
            createUserId: null,      //单据创建人

            // tableScrollLeft: 0,       //table滚动条距离左边的距离


            recordInvoiceType: null,     //记录选中的 发票类型
        }
    },
    mounted () {
        // let tableScroll = document.getElementById('bills_tb').querySelector('.ant-table-body');
        // tableScroll.scroll(this.tableScrollLeft, 0);
        //获取单据table的高度

        if (this.showModel == 'detail') {
            //工序汇报移除了table 故不需要获取高度
        } else {
            setTimeout(() => {
                let tableBox = document.getElementById('bills_tb');
                let tableHeight = tableBox.getBoundingClientRect().height;

                let tableMask = document.getElementsByClassName('edit-mask');
                tableMask[0].style.height = tableHeight - 50 + 'px';
                tableMask[0].style.top = 34 + 'px';
            }, 500)
        }
    },
    watch: {
        visible (value) {
            if (value) {
                document.body.addEventListener("click", this.closeMenu);
            } else {
                document.body.removeEventListener("click", this.closeMenu);
            }
        },
        dataSource (value) {
            this.count = value.length;
        },
        invoiceData: {
            handler (newval) {
                if (Object.keys(newval).length > 0 && (newval.generateSourceCode == this.sourceCode || newval.generateSourceCode == this.businessType)) {
                    console.log('进来了。。。。。。。。。。。。。')
                    this.editClickOrder(newval, 'iscreate')
                }
            },
            immediate: true,
        },
    },
    computed: {
        invoiceData () {
            return this.$store.state.order.invoiceData;
        },
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
        }),
    },
    beforeCreate () {
        this.form = this.$form.createForm(this, { name: "order" });
    },
    created () {
        this.getUnitData();
        this.getGrouplist();
    },
    methods: {
        //获取计量单位（单计量）
        getUnitData () {
            let postData = {
                //查询条件
                current: 1,
                size: 1000,
                unitGroupId: 0
            };
            pageList(postData).then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    const { records, total, current, size } = data;
                    this.unitData = records;
                }
            }).catch(error => { });
        },
        //计量单位组下面的组单位
        getGrouplist () {
            let requestData = {
                current: 1,
                size: 1000,
                unitGroupId: -1
            }
            pageList(requestData).then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    const { records } = data;
                    this.unitsDataDetails = records;
                }
            }).catch(error => { });
        },
        //根据id返回 非主计量的 辅助计量组
        returnGroupUnits (id) {
            let elementId = null;
            let units = [];
            this.unitsDataDetails.forEach(element => {
                if (id == element.id) {
                    elementId = element.unitGroupId;
                }
            });
            this.unitsDataDetails.forEach(element => {
                if (elementId == element.unitGroupId && !element.isMainUnit) {
                    units.push(element);
                }
            });
            return units;
        },


        //强制刷新表格
        reload () {
            this.isRouterAlive = false;
            this.$nextTick(function () {
                this.isRouterAlive = true;
            });
        },
        //初始化表字段
        initForm (type) {
            console.log(type)
            /**
             * type == 1新增
             * type == 2修改
             */
            handleDynamicData(this.sourceCode).then(res => {
                this.dynamicFormData = res;

                this.onFillData = res.filter(item => {
                    return item.onFill === true;
                })

                //表头字段名
                this.orderHeaderData = res.filter(item => {
                    return item.dataTab === '表头';
                });

                //隐藏表头的仓库字段
                if (this.headerInWherehouse) {
                    this.orderHeaderData.forEach(e => {
                        if (e.code == 'warehouseId') {
                            e.onOff = false;
                        }
                    });
                }

                //表尾字段名
                this.orderFooterData = res.filter(item => {
                    return item.dataTab === '表尾';
                })

                //明细
                this.orderDetailData = res.filter(item => {
                    return item.dataTab === '明细';
                })

                //物料明细
                this.orderDetailBomData = res.filter(item => {
                    return item.dataTab === '物料明细';
                })
                this.columnsBom = this.regroupTableColumns(this.orderDetailBomData);

                const editCol = (dd) => {
                    let aaa = dd.filter(res => { return res.onEdit })
                    let back = [];
                    aaa.forEach(item => {
                        back.push(item.code)
                    });
                    return back;
                }
                let columnsBomTemp = editCol(this.orderDetailBomData)
                delete columnsBomTemp[0];
                this.editColumnBom = columnsBomTemp;

                //明细（表格字段名）
                this.columns = this.regroupTableColumns(this.orderDetailData);
                console.log(this.columns)
                for (let i = 0; i < this.columns.length; i++) {
                    if (this.columns[i].dataIndex != "number") {
                        this.slotArray.push(this.columns[i].dataIndex);
                    }
                }
                //设置表头日期默认值
                this.orderHeaderData.forEach(item => {
                    if (item.columnType == '日期' && item.value == '') {
                        this.$set(item, 'value', getDate.getCurrentMoment().format('YYYY-MM-DD'))
                    }
                })
                //设置表尾日期默认值
                this.orderFooterData.forEach(item => {
                    if (item.columnType == '日期' && item.value == '') {
                        this.$set(item, 'value', getDate.getCurrentMoment().format('YYYY-MM-DD'))
                    }
                })

                //设置下拉默认选中第一个
                this.dynamicFormData.forEach(element => {
                    if (element.columnType == '下拉' && element.val != '') {
                        this.$set(element, 'value', element.val.split(',')[0])
                    }

                    if (element.columnType == '下拉选择' && element.val != '' && element.val != null) {
                        console.log(element.code);
                        if (element.code == 'qualityInspectionState') {
                            this.$set(element, 'value', JSON.parse(element.val)[0].key)
                        } else {
                            let defaultArray = this.formatSelectJsonVal(element.val);
                            console.log(defaultArray);
                            this.$set(element, 'value', defaultArray[0].key)
                        }
                    }
                });

                //领退补
                if (this.isPRF) {
                    this.orderHeaderData.forEach(e => {
                        if (e.code == 'businessType') {
                            this.$set(e, 'value', this.businessType)
                        }
                    });
                }

                if (type == 1) {
                    this.orderId = '';
                    // this.editData = [];
                    this.getCode();//获取单据编号
                    this.initTable(type);//初始化table
                }

                this.dataSourceBom = [];
                this.dataSourceRoute = [];

            })
        },
        //初始化table数据
        initTable (type) {
            this.dataSource = [];
            this.reload();
            const dataSource = [];

            //判断屏幕的宽度来设定渲染多少行
            // let w = document.body.clientWidth;//当前可视窗口宽度
            // console.log(w);
            // if(w >= 1920){
            //     this.dataSourceNumber = 10;
            // }

            for (let i = 0; i < this.dataSourceNumber; i++) {
                let array = {
                    number: i + 1,
                };
                dataSource.push(array);
            }
            Object.assign(this.dataSource, dataSource);
            this.addTotal();//添加合计
        },

        //添加合计
        addTotal () {
            this.count = this.dataSource.length + 1;

            this.dataSource.push({
                number: "合计",
                name: 'total',
                tax: 0,                  //税额
                baseQuantity: 0,         //数量
                amount: 0,             //金额
                includeTaxAmount: 0,   //含税金额
            });
            //刷新合计
            this.totalCalculate();
        },
        //提交数据
        submitServer (type) {
            //type 在其他页面调用了该组件用type来做必填等相关操作的区分
            //现：type:1.生产订单页面(生单)

            const { dataSource, orderHeaderData, orderFooterData, dynamicFormData } = this;

            //拿出表头、表尾自定义字段
            let customField = dynamicFormData.filter(item => {
                return item.dataType != 1 && (item.dataTab == '表头' || item.dataTab == '表尾');
            })
            let d = {
                detail: dataSource,
                header: orderHeaderData.filter(item => { return item.dataType == 1 }),
                footer: orderFooterData.filter(item => { return item.dataType == 1 }),
                customField: customField,
            }
            //文字转换为id
            console.log(d.detail);
            for (const key in d.detail) {
                d.detail[key].baseUnit ? d.detail[key].baseUnit = d.detail[key].baseUnit_temp_id : '';//主计量
                d.detail[key].subUnit ? d.detail[key].subUnit = d.detail[key].subUnit_temp_id : '';//辅计量
            }

            console.log(dataSource);
            dynamicFormData.forEach(element => {
                if (element.columnType == '下拉选择') {
                    dataSource.forEach((item, key) => {
                        item[element.code] = item[element.code + 'Id']
                    })
                }
            });
            //设置日期默认值
            for (const key in d.header) {
                if (d.header[key].columnType == '日期' && d.header[key].value == '') {
                    d.header[key].value = getDate.getCurrentMoment().format('YYYY-MM-DD');
                }
            }

            //过滤自定义字段
            let defineData = dynamicFormData.filter(item => item.dataType != 1);

            let requestData = this.submitRegData(d, defineData);

            for (const key in orderHeaderData) {
                if (orderHeaderData[key].columnType == '搜索选择') {
                    //用于页面展示 新增...Name字段
                    if (orderHeaderData[key].code.indexOf('Id') != '-1') {
                        let tempname = orderHeaderData[key].code.substring(0, orderHeaderData[key].code.length - 2) + 'Name';

                        console.log(orderHeaderData[key].code, tempname);
                        this.$set(requestData, tempname, orderHeaderData[key].valueName);
                        this.$set(requestData, orderHeaderData[key].code, orderHeaderData[key].valueId);
                    }
                }
            }

            if (this.orderId) {
                this.$set(requestData, 'id', this.orderId);
            }
            //订金金额判断
            let numReg = /^[0-9][0-9]*(\.[0-9]{1,8})?$/;//整数或者1-8位小数
            if (requestData.earnestMoney && requestData.earnestMoney != null) {
                if (!numReg.test(requestData.earnestMoney)) {
                    this.$message.warning('订金金额只能是数字！')
                    return;
                }
            }

            console.log('提交数据：', requestData)

            //必填判断
            console.log(this.onFillData)
            let headerAndFooterVerify = this.onFillData.filter(item => item.dataTab == '表头' || item.dataTab == '表尾');

            if (this.headerInWherehouse) {//隐藏表头的仓库字段 同时去除必填 控制
                headerAndFooterVerify.forEach((element, index) => {
                    if (element.code == 'warehouseId') {
                        headerAndFooterVerify.splice(index, 1); //删除下标为i的元素
                    }
                });
            }
            for (const key in requestData) {//表头和表尾的必填判断
                for (const onkey in headerAndFooterVerify) {
                    if (key != 'orderDetailList' && headerAndFooterVerify[onkey].code == key && !headerAndFooterVerify[onkey].value) {
                        this.$message.warning(`${headerAndFooterVerify[onkey].name}必须填写!`)
                        return;
                    }
                }
            }

            let detailVerify = this.onFillData.filter(item => item.dataTab == '明细' && item.onEdit)
            let b = requestData.orderDetailList;

            //参数type=1 判断
            for (let index = 0; index < b.length; index++) {
                const item = b[index];
                if (!item.officeName) {
                    this.$message.warning(`请选择生产车间`)
                    return;
                } else {
                    let name = JSON.parse(JSON.stringify(item.officeId));
                    item.officeId = item.officeName;
                    item.officeName = name;
                }
            }




            //采购入库 头部选择仓库过后，明细中仓库同步修改
            if (this.isHideWherehouse) {//isHideWherehouse:证明是采购入库
                requestData.orderDetailList.forEach(cai => {
                    cai.warehouseName = requestData.warehouseName;
                    cai.warehouseId = requestData.warehouseId;
                    cai.warehouseCode = requestData.warehouseCode;
                });
            }

            //采购到货，采购退货  头部有供应商的 明细中供应商同步
            if (this.isDetailCrmId) {
                if (requestData.crmId) {
                    requestData.orderDetailList.forEach(cai => {
                        cai.crmId = requestData.crmId;
                        cai.crmName = requestData.crmName;
                    });
                }
            }


            if (b.length == 0) {
                this.$message.warning('单据明细不能为空')
                return;
            }
            for (const key in b) {//明细的必填判断
                let a = b[key];
                for (const onkey in detailVerify) {
                    if (!a[detailVerify[onkey].code]) {
                        this.$message.warning(`${detailVerify[onkey].name}必须填写!`)
                        return;
                    }
                }
            }

            //---出入库需要传递的参数
            this.$set(requestData, 'dataSource', this.sourceCode)
            this.$set(requestData, 'receiveDeliverType', this.receiveDeliverType);//1收，2发
            //---出入库需要传递的参数

            //合并数据来源
            Object.assign(requestData, this.sourceVoucherData);
            console.log("数据来源：", this.sourceVoucherData, this.sourceVoucherDetails);

            // if (!requestData.id && requestData.sourceVoucherId) {
            //     //合并明细来源id
            //     for (let i = 0; i < requestData.orderDetailList.length; i++) {
            //         if (!this.sourceVoucherDetails[i]) {
            //             this.$message.warning('生单或选单不允许新增数据');
            //             return;
            //         }
            //         this.$set(requestData.orderDetailList[i], 'sourceDetailId', this.sourceVoucherDetails[i].sourceDetailId);
            //     }
            //     console.log('提交的明细', requestData.orderDetailList, '明细来源id：', this.sourceVoucherDetails);
            // }

            let mxDetails = requestData.orderDetailList;
            //采购发票 判断发票类型和业务类型
            if (this.$route.path == '/procurement/purchaseInvoice') {
                //记录选中的 发票类型
                if (requestData.businessType == 99) {
                    if (this.recordInvoiceType != 0) {
                        this.$message.warning('采购退货时，发票类型必须是“负发票”');
                        return;
                    }
                    for (let i = 0; i < mxDetails.length; i++) {
                        if (mxDetails[i].baseQuantity > 0) {
                            this.$message.warning('采购退货时，物料数量必须小于0');
                            return;
                        }
                    }
                } else if (requestData.businessType == 1 || requestData.businessType == 2) {
                    if (this.recordInvoiceType == 0) {
                        this.$message.warning('发票类型必须是“正发票”');
                        return
                    }
                }
            }

            //销售发票 判断发票类型和业务类型
            if (this.$route.path == '/sale/saleInvoice') {
                //记录选中的 发票类型
                if (requestData.businessType == 98) {
                    if (this.recordInvoiceType != 0) {
                        this.$message.warning('销售退货时，发票类型必须是“负发票”');
                        return;
                    }
                    for (let i = 0; i < mxDetails.length; i++) {
                        if (mxDetails[i].baseQuantity > 0) {
                            this.$message.warning('销售退货时，物料数量必须小于0');
                            return;
                        }
                    }

                } else if (requestData.businessType == 3) {
                    if (this.recordInvoiceType == 0) {
                        this.$message.warning('发票类型必须是“正发票”');
                        return
                    }
                }
            }

            //业务为退货的数量必须为 负数
            // if (requestData.businessType == 96 ||
            //     requestData.businessType == 97 ||
            //     requestData.businessType == 98 ||
            //     requestData.businessType == 99 ||
            //     requestData.businessType == 5 ||
            //     requestData.businessType == 31 ||
            //     requestData.businessType == 32
            // ) {
            //     for (let i = 0; i < mxDetails.length; i++) {
            //         if (mxDetails[i].baseQuantity > 0) {
            //             this.$message.warning('业务类型为退货时，物料数量必须是负数');
            //             return;
            //         }
            //     }
            // }

            //领退补页面，业务类型定死
            if (this.sourceCode == 'RRS') {
                requestData.businessType = this.businessType;
            }

            //提交保存数据
            if (this.isSaveRun) {
                this.isSaveRun = false;
                this.submit(requestData);
            }
        },
        /**
         * 修改&&选单&&生单
         * type=='ischoose' 选单
         * type=='iscreate' 生单
         */
        editClickOrder (record, type) {
            console.log(record, type)

            this.thisPageData = record;
            this.createUserId = record.createUserId;//单据创建人id

            if (!type) {
                this.editMask = true;//遮罩
            } else {
                this.editMask = false;
                this.showModel = 'order';
            }
            //先清空数据
            this.dataSource = {};
            for (let i = 0; i < this.dynamicFormData.length; i++) {
                if (this.dynamicFormData[i].columnType == '搜索选择') {
                    this.$set(this.dynamicFormData[i], 'valueId', '');
                    this.$set(this.dynamicFormData[i], 'valueName', '')
                    this.$set(this.dynamicFormData[i], 'value', '')
                } else {
                    this.$set(this.dynamicFormData[i], 'value', '');
                }
            }
            //end先清空数据



            if (type) {
                this.sourceVoucherData = {};
                this.sourceVoucherDetails = [];
                //数据来源
                this.sourceVoucherData = {
                    'sourceVoucherId': record.sourceVoucherId,
                    'sourceVoucherCode': record.sourceVoucherCode,
                    'sourceVoucherDate': record.sourceVoucherDate,
                    'sourceVoucherType': record.sourceVoucherType
                }
                //明细中添加数据来源id
                record.detailList.forEach(element => {
                    element.sourceDetailId = element.id;
                    // this.sourceVoucherDetails.push({
                    //     sourceDetailId: element.id
                    // })
                });
                record = this.copyRemoveIdData(JSON.stringify(record));

                //领退补
                this.orderHeaderData.forEach(e => {
                    if (e.code == 'businessType') {
                        e.onEdit = false;
                    }
                });
            }

            console.log('==========================当前数据===================', record)
            this.dataSource = record.detailList;
            this.orderId = record.id;
            this.voucherState = record.voucherState;


            //补足表格
            if (this.dataSource.length < this.dataSourceNumber) {
                for (let i = this.dataSource.length; i < this.dataSourceNumber; i++) {
                    let array = {
                        number: i + 1,
                    };
                    this.dataSource.push(array);
                }
                this.addTotal();//添加合计
            } else {
                for (let i = 0; i < 2; i++) {
                    let array = {
                        number: i + 1,
                    };
                    this.dataSource.push(array);
                }
                this.addTotal();//添加合计
            }
            this.reload()
            //自定义字段
            let defineData = this.dynamicFormData.filter(item => item.dataType != 1);


            for (let i = 0; i < this.dataSource.length; i++) {

                if (this.dataSource[i].unitId) {
                   
                    //单计量
                    this.unitData.forEach(item => {
                        if (item.id == this.dataSource[i].unitId) {
                            this.dataSource[i].baseUnit = item.name;
                            this.dataSource[i].baseUnitName = item.name;
                            this.dataSource[i].baseUnit_temp_id = item.id;//单计量id
                            this.dataSource[i].unitId = item.id;
                        }
                    })
                }

                if (this.dataSource[i].unitGroupId) {
                    //多计量
                    this.unitsDataDetails.forEach(item => {
                        if (item.id == this.dataSource[i].unitGroupId) {
                            this.dataSource[i].baseUnit = item.name;
                            this.dataSource[i].baseUnitName = item.name;
                            this.dataSource[i].baseUnit_temp_id = item.id;//多计量
                            this.dataSource[i].unitGroupId = item.id;
                        }
                    })

                    //辅助计量数据
                    this.unitsAssistSelect = this.returnGroupUnits(this.dataSource[i].unitGroupId);
                    //辅助计量修改时设值
                    this.unitsAssistSelect.forEach(item => {
                        if (item.id == this.dataSource[i].subUnit) {
                            this.dataSource[i].subUnit = item.name;
                            this.dataSource[i].subUnit_temp_id = item.id;
                        }
                    })
                }

                //明细自定义值的转换
                if (this.dataSource[i].defineFields) {
                    let defineItem = JSON.parse(this.dataSource[i].defineFields);
                    for (const dekey in defineItem) {
                        for (const allkey in defineData) {
                            //根据id找到code
                            if (defineData[allkey].code == dekey) {
                                this.$set(this.dataSource[i], defineData[allkey].code, defineItem[dekey])
                            }
                        }
                    }
                }

                //是否
                this.dynamicFormData.forEach(element => {
                    if (element.columnType == '下拉选择') {
                        for (const key in this.dataSource[i]) {
                            if (element.code == key) {
                                //1：当前选中的id  2：下拉数组
                                console.log(element.code);
                                let label = this.handleDownChoice(this.dataSource[i][key], element.val);
                                this.$set(this.dataSource[i], key + 'Id', this.dataSource[i][key])
                                this.$set(this.dataSource[i], key, label)
                            }
                        }
                    }
                });

            }
            console.log(this.dataSource)



            for (let i = 0; i < this.orderHeaderData.length; i++) {
                for (const key in record) {
                    if (this.orderHeaderData[i].code == key) {
                        if (this.orderHeaderData[i].columnType == '搜索选择') {
                            //用于页面展示 新增...Name字段
                            if (this.orderHeaderData[i].code.indexOf('Id') != '-1') {
                                let tempname = this.orderHeaderData[i].code.substring(0, this.orderHeaderData[i].code.length - 2) + 'Name';
                                this.$set(this.orderHeaderData[i], 'valueId', record[key]);
                                this.$set(this.orderHeaderData[i], 'valueName', record[tempname])
                                this.$set(this.orderHeaderData[i], 'value', record[tempname])
                            }

                            // if(this.orderHeaderData[i].code == 'warehouseId'){
                            //     console.log('仓库仓库仓库',this.orderHeaderData[i])
                            // }
                        } else {
                            //如果是选单（选单等于新增） 单据编号不赋值
                            if (type == 'ischoose' || type == 'iscreate') {
                                if (this.orderHeaderData[i].code == 'voucherCode') {
                                    this.getCode();//获取新的单据编号
                                } else {
                                    this.$set(this.orderHeaderData[i], 'value', record[key]);
                                }

                            } else {
                                this.$set(this.orderHeaderData[i], 'value', record[key]);
                            }
                        }

                        //采购发票，采购入库，销售出库
                        if (this.orderHeaderData[i].code == 'businessType' && (this.sourceCode == 'PurchaseInvoice' || this.sourceCode == 'PurchaseReceiveVoucher')) {
                            this.$set(this.orderHeaderData[i], 'onEdit', false);
                        }

                        // 退货单 选单时候，业务类型的更改 
                        //采购退货99，采购退货（冲抵）97，
                        if (this.sourceCode == 'PuArrival' && this.businessType == 1) {
                            if (this.orderHeaderData[i].code == 'businessType') {
                                if (record.businessType != 99 && record.businessType != 97) {
                                    this.$set(this.orderHeaderData[i], 'value', 99);
                                } else {
                                    this.$set(this.orderHeaderData[i], 'value', record.businessType);

                                }
                            }
                        }
                        //销售退货 98,销售退货（冲抵）96
                        if (this.sourceCode == 'SaleDelivery' && this.businessType == 1) {
                            if (this.orderHeaderData[i].code == 'businessType') {
                                if (record.businessType != 98 && record.businessType != 96) {
                                    this.$set(this.orderHeaderData[i], 'value', 98);
                                } else {
                                    this.$set(this.orderHeaderData[i], 'value', record.businessType);

                                }
                            }
                        }
                    }
                }

                //头部自定义值的转换
                if (record.defineFields) {
                    let recoedDefine = JSON.parse(record.defineFields)
                    for (const key in recoedDefine) {
                        if (this.orderHeaderData[i].code == key) {
                            this.$set(this.orderHeaderData[i], 'value', recoedDefine[key]);
                        }
                    }
                }

            }

            for (let i = 0; i < this.orderFooterData.length; i++) {
                for (const key in record) {
                    if (this.orderFooterData[i].code == key) {
                        if (this.orderFooterData[i].columnType == '搜索选择') {
                            if (this.orderFooterData[i].code.indexOf('Id') != '-1') {
                                let tempname = this.orderFooterData[i].code.substring(0, this.orderFooterData[i].code.length - 2) + 'Name';
                                this.$set(this.orderFooterData[i], 'valueId', record[key]);
                                this.$set(this.orderFooterData[i], 'valueName', record[tempname])
                                this.$set(this.orderFooterData[i], 'value', record[tempname])
                            }
                        } else {
                            if (this.orderFooterData[i].code == key) {
                                this.$set(this.orderFooterData[i], 'value', record[key])
                            }
                        }
                    }
                }

                //底部自定义值的转换
                if (record.defineFields) {
                    let recoedDefine = JSON.parse(record.defineFields)
                    for (const key in recoedDefine) {
                        if (this.orderFooterData[i].code == key) {
                            this.$set(this.orderFooterData[i], 'value', recoedDefine[key]);
                        }
                    }
                }
            }

            this.loading = false;
            // this.$store.commit('SET_ARR', {})


            setTimeout(() => {
                this.$store.commit('SET_ARR', {})
            }, 1000);
            // console.log(this.invoiceData, Object.keys(this.invoiceData).length);
        },
        onCellChange (indexTable, dataIndex, value) {
            console.log('返回值', indexTable, dataIndex, value);

            //修改明细table数据
            const dataSource = [...this.dataSource];
            const target = dataSource.find((item, index) => index === indexTable);
            console.log('明细表点击的行数——————', value, this.dataSource);
            let runAddDataSource = true;

            if (dataIndex == 'inventoryCode') {

                //重置当前列数据
                for (const key in target) {
                    target[key] = ''
                }

                //判断物料是否重复
                // for (let i = 0; i < this.dataSource.length; i++) {
                //     if (value.id == this.dataSource[i].inventoryId) {
                //         this.$message.error('物料已经存在当前单据,不能重复添加', 1);
                //         runAddDataSource = false;
                //         break;
                //     }
                // }

                //物料名称
                if (target && runAddDataSource) {
                    target[dataIndex] = value.inventoryCode;//物料编码
                    target['inventoryId'] = value.id;//物料名称
                    target['inventoryName'] = value.inventoryName;//物料名称
                    target['inventorySpecification'] = value.inventorySpecification;//规格型号
                    target['taxRate'] = value.taxRate ? value.taxRate : 13;//税率

                    //处理库存初期，仓库
                    this.orderHeaderData.forEach(element => {
                        if (element.code == 'warehouseId') {
                            target['warehouseId'] = element.valueId;
                            target['warehouseName'] = element.valueName;

                        }
                    });


                    if (value.unitType == '单计量') {
                        target['baseUnit'] = value.unitName;//单计量
                        target['baseUnitName'] = value.unitName;//单计量
                        target['baseUnit_temp_id'] = value.unitId;//单计量id
                        target['unitId'] = value.unitId;//单计量id
                    } else {
                        for (let i = 0; i < this.unitsDataDetails.length; i++) {
                            if (this.unitsDataDetails[i].id == value.mainUnit) {
                                target['baseUnit'] = this.unitsDataDetails[i].name;//主计量
                                target['baseUnitName'] = this.unitsDataDetails[i].name;//主计量
                                target['baseUnit_temp_id'] = this.unitsDataDetails[i].id;//主计量id
                                target['baseUnitId'] = this.unitsDataDetails[i].id;
                                target['unitGroupId'] = this.unitsDataDetails[i].id;
                            }
                        }

                        //辅助计量数据
                        this.unitsAssistSelect = [];
                        this.unitsDataDetails.forEach(element => {
                            if (element.unitGroupId == value.unitGroupId && !element.isMainUnit) {
                                this.unitsAssistSelect.push(element);
                            }
                        });
                        console.log(this.unitsAssistSelect);
                        target['subUnit'] = this.unitsAssistSelect[0].name;
                        target['subUnit_temp_id'] = this.unitsAssistSelect[0].id;
                        target['unitExchangeRate'] = this.unitsAssistSelect[0].changeRate;  //换算率
                        console.log('辅计量默认值---------', this.unitsAssistSelect[0].name, this.unitsAssistSelect[0].id)
                    }

                    this.$nextTick(() => {
                        this.dataSource = dataSource;
                        this.reload();
                    })
                }
            } else if (dataIndex == 'projectCode' || dataIndex == 'projectName') {
                //项目
                if (dataIndex == 'projectCode') {
                    target[dataIndex] = value.code;
                    target['projectId'] = value.id;
                } else {
                    target[dataIndex] = value.name;
                    target['projectId'] = value.id;
                }

                this.$nextTick(() => {
                    this.dataSource = dataSource;
                    this.reload();
                });

            } else if (dataIndex == 'warehouseName') {
                //仓库
                target[dataIndex] = value.whName;
                target['warehouseId'] = value.id;
                target['warehouseCode'] = value.whCode;
                this.$nextTick(() => {
                    this.dataSource = dataSource;
                    this.reload();
                });
            } else if (dataIndex == 'crmName') {
                //供应商
                target[dataIndex] = value.vendorName;
                target['crmId'] = value.id;
                this.$nextTick(() => {
                    this.dataSource = dataSource;
                    this.reload();
                });
            } else if (dataIndex == 'officeName' || dataIndex == 'officeId') {
                //车间，部门
                //id和name相反,？，编辑项为什么要返回offceid
                if (dataIndex == 'officeId') {
                    target[dataIndex] = value.officeName;
                    target['officeName'] = value.id;
                } else {
                    target[dataIndex] = value.officeName;
                    target['officeId'] = value.id;
                }

                this.$nextTick(() => {
                    this.dataSource = dataSource;
                    this.reload();
                });
            } else if (dataIndex == 'inventoryLocationCode' || dataIndex == 'inventoryLocationName') {
                //货位
                if (dataIndex == 'inventoryLocationCode') {
                    target[dataIndex] = value.code;
                    target['inventoryLocationName'] = value.name;
                    target['inventoryLocationId'] = value.id;
                } else {
                    target[dataIndex] = value.name;
                    target['inventoryLocationId'] = value.id;
                    target['inventoryLocationCode'] = value.code;
                }
                this.$nextTick(() => {
                    this.dataSource = dataSource;
                    this.reload();
                });
            } else if (dataIndex == 'workProcedureName') {
                //工序
                target[dataIndex] = value.name;
                target['workProcedureId'] = value.id;
            } else if (dataIndex == 'productionLineName') {
                //生产线
                target[dataIndex] = value.name;
                target['productionLineId'] = value.id;
            } else if (dataIndex == 'teamName') {
                //班组
                target[dataIndex] = value.name;
                target['teamId'] = value.id;
            } else if (dataIndex == 'bomName') {
                //bom版本号
                target[dataIndex] = value.name;
                target['bomId'] = value.id;
                this.$nextTick(() => {
                    this.dataSource = dataSource;
                    this.reload();
                });
                //加工单获取物料明细
                // this.getBomDetails(value.id, target.baseQuantity);

                if (value.processRouteId) {
                    //如果选择的物料明细中有默认工艺路线
                    target['processRouteName'] = value.processRouteName;
                    target['processRouteId'] = value.processRouteId;
                    // this.getRouteDetails(value.processRouteId);
                }
            } else if (dataIndex == 'processRouteName') {
                //工艺路线
                target[dataIndex] = value.name;
                target['processRouteId'] = value.id;
                this.$nextTick(() => {
                    this.dataSource = dataSource;
                    this.reload();
                });
                //加工单获取工艺路线
                // this.getRouteDetails(value.id);
            } else if (dataIndex == 'baseQuantity' || dataIndex == 'price' || dataIndex == 'includeTaxPrice' || dataIndex == 'taxRate' || dataIndex == 'unitExchangeRate' || dataIndex == 'subQuantity' || dataIndex == 'subUnit') {

                /**
                * price:单价
                * includeTaxPrice:含税单价
                * baseQuantity:数量
                * taxRate：税率
                * amount:金额
                * includetaxAmount:含税金额
                * 
                * unitExchangeRate:换算率
                * subQuantity:辅计量数量
                */
                if (target && value) {

                    //辅助计量改变的时候 换算率赋值后也要计算 dataIndex == 'subUnit'
                    if (dataIndex != 'subUnit') {
                        target[dataIndex] = value;
                    } else {
                        console.log('辅计量选中的值---------', value)
                        target['subUnit'] = value.name;
                        target['subUnit_temp_id'] = value.id;//辅计量id
                        target['unitExchangeRate'] = value.unitExchangeRate;  //换算率
                    }


                    //==========================换算率相关

                    //输入换算率的时候
                    if (dataIndex == 'unitExchangeRate' || value.unitExchangeRate) {
                        //辅计量必须选择
                        if (!target.subUnit || target.subUnit == null || target.subUnit == '' || !target.subQuantity) {
                            this.$message.error('辅计量 和 辅计量数量 必须存在值');
                            return;
                        } else {
                            if (target.baseQuantity) {
                                target['subQuantity'] = '';
                                //辅计量数量=主计量数量 / 换算率
                                let n = Number(target.baseQuantity) / Number(target.unitExchangeRate);
                                target['subQuantity'] = n.toFixed(2);
                            }
                        }
                    }

                    //输入辅计量数量的时候
                    if (dataIndex == 'subQuantity') {
                        //辅计量必须选择
                        if (!target.subUnit || target.subUnit == null || target.subUnit == '') {
                            this.$message.error('辅计量必须选择');
                            return;
                        } else {
                            // if (target.baseQuantity) {
                            //     //换算率 = 主计量数量/辅计量数量
                            //     let n = Number(target.baseQuantity) / Number(target.subQuantity);
                            //     target['unitExchangeRate'] = n.toFixed(2);
                            // } else {
                            //主计量数量 = 辅计量数量*换算率
                            let n = Number(target.subQuantity) * Number(target.unitExchangeRate);
                            target['baseQuantity'] = n.toFixed(2);
                            // }
                        }
                    }
                    //输入数量的时候
                    if (dataIndex == 'baseQuantity') {
                        //输入数量  并且辅计量数量存在
                        if (target.unitExchangeRate) {
                            //辅计量数量 = 主计量数量*换算率
                            let total = Number(target.baseQuantity) / Number(target.unitExchangeRate);
                            target['subQuantity'] = total.toFixed(2);
                        }
                    }

                    //☆☆☆☆☆☆☆触发加工单物料数量的计算☆☆☆☆☆☆☆
                    // if (dataIndex == 'baseQuantity' || dataIndex == 'unitExchangeRate' || dataIndex == 'subQuantity')
                    // if (this.sourceCode == 'ProductionWork' && this.dataSourceBom) {//页面如果是加工单
                    //     if (this.dataSourceBom.length > 0) {//判断物料明细是否有数据
                    //         this.dataSourceBomNumber = Number(target.baseQuantity);
                    //         this.dataSourceBom.forEach(item => {
                    //             let num = Number(target.baseQuantity) * Number(item.baseRequireQuantity);
                    //             item.requireQuantity = num;
                    //         });
                    //     }
                    // }

                    //==========================换算率相关

                    //计算单价
                    if (dataIndex == 'includeTaxPrice') {
                        target['price'] = '';
                        if (target.includeTaxPrice && target.taxRate) {
                            let total = Number(target.includeTaxPrice) / (1 + target.taxRate / 100);
                            target['price'] = total.toFixed(2);
                        } else {
                            target['price'] = Number(target.includeTaxPrice);
                        }
                    }
                    //计算含税单价
                    if (dataIndex == 'price') {
                        target['includeTaxPrice'] = '';
                        if (target.price && target.taxRate) {
                            let total = Number(target.price) * (1 + target.taxRate / 100);
                            target['includeTaxPrice'] = total.toFixed(2);
                        } else {
                            target['includeTaxPrice'] = Number(target.price);
                        }
                    }

                    if (dataIndex == 'taxRate') {//输入税率的情况
                        if (!target.price && !target.includeTaxPrice) {//1.单价和含税单价都不存在
                            return;
                        } else {//两个都存在（以单价为准）
                            target['includeTaxPrice'] = '';//清空含税单价
                            if (target.price && target.taxRate) {
                                let total = Number(target.price) * (1 + target.taxRate / 100);
                                target['includeTaxPrice'] = total.toFixed(2);
                            } else {
                                target['includeTaxPrice'] = Number(target.price);
                            }
                        }
                    }

                    //算税额
                    if (target.baseQuantity && target.price && target.taxRate) {
                        //税额= 单价*数量*税率
                        let tax = Number(target.baseQuantity) * Number(target.price) * Number(target.taxRate) / 100
                        target['tax'] = tax.toFixed(4);
                    }

                    if (target.baseQuantity && target.price) {
                        //数量*单价=金额
                        let total = Number(target.baseQuantity) * Number(target.price);
                        target['amount'] = total.toFixed(2);
                    }

                    // if (target.baseQuantity && target.includeTaxPrice) {
                    //     //数量*含税单价=含税金额
                    //     let total = Number(target.baseQuantity) * Number(target.includeTaxPrice);
                    //     target['includeTaxAmount'] = total.toFixed(2);
                    // }

                    if (target.amount && target.tax) {
                        //含税金额 = 金额 + 税额
                        let total = Number(target.amount) + Number(target.tax);
                        target['includeTaxAmount'] = total.toFixed(2);
                    }


                    this.$nextTick(() => {
                        this.dataSource = dataSource;
                        this.reload();
                    })
                }
            } else if (value.columnType == '日期') {
                if (target) {
                    target[dataIndex] = value.value;

                    this.$nextTick(() => {
                        this.dataSource = dataSource;
                    });
                }
            } else if (value.columnType == '下拉选择') {
                if (target) {
                    target[dataIndex] = value.name;
                    target[dataIndex + 'Id'] = value.id;
                    this.$nextTick(() => {
                        this.dataSource = dataSource;
                    });
                }
            } else {
                if (target) {
                    this.$nextTick(() => {
                        target[dataIndex] = value;
                        this.dataSource = dataSource;
                    });
                    this.reload();
                }
            }
            //修改数据后刷新合计
            this.totalCalculate();
        },
        showDrawer () {
            //右侧搜索抽屉
            this.$refs.searchList.onOpen(this.sourceCode)
        },


        //=============================== 表头的搜索选择 ==========================
        setValue (data) {
            console.log(data);
            const { orderHeaderData } = this;

            if (data.codesName == 'warehouseId' && !orderHeaderData.some(e => e.code == 'warehouseCode')) {
                orderHeaderData.push({
                    code: "warehouseCode",
                    columnType: "文本",
                    name: '仓库编码',
                    dataType: 1,
                    onEdit: false,
                    onFill: true,
                    onOff: true,
                    value: data.whCode,
                    valueName: data.whCode,
                })
            }

            for (let i = 0; i < orderHeaderData.length; i++) {
                if (orderHeaderData[i].code == data.codesName) {
                    this.$set(orderHeaderData[i], 'value', data.name)
                    this.$set(orderHeaderData[i], 'valueId', data.id)
                    this.$set(orderHeaderData[i], 'valueName', data.name)
                }

                if (data.codesName == 'purchaseTypeId' && orderHeaderData[i].code == 'purchaseTypeCode') {
                    //采购类型编码
                    this.$set(orderHeaderData[i], 'valueName', data.code)
                    this.$set(orderHeaderData[i], 'value', data.code)
                }

                if (data.codesName == 'warehouseId' && orderHeaderData[i].code == 'warehouseCode') {
                    //仓库编码
                    this.$set(orderHeaderData[i], 'valueName', data.whCode)
                    this.$set(orderHeaderData[i], 'value', data.whCode)
                }
            }
            Object.assign(this.orderHeaderData, orderHeaderData)
            console.log(this.orderHeaderData)

            //改变 发票表单  的标题颜色
            if ((this.$route.path == '/procurement/purchaseInvoice' || this.$route.path == '/sale/saleInvoice') && data.codesName == 'invoiceTypeId') {
                //记录选中的 发票类型
                this.recordInvoiceType = data.type;

                if (data.type == 0) {
                    document.querySelectorAll("h2.text-center")[0].style.color = 'red'
                    // console.log(document.querySelectorAll("h2.text-center"));

                    console.log(this.dataSource)
                } else {
                    document.querySelectorAll("h2.text-center")[0].style.color = 'rgba(0,0,0,.85)'
                }
            }

        },
        onChangeTime (backData) {
            //日期修改
            const { orderHeaderData } = this;
            for (let i = 0; i < orderHeaderData.length; i++) {
                if (orderHeaderData[i].code == backData.code) {
                    this.$set(orderHeaderData[i], 'value', backData.dateString)
                }
            }
            Object.assign(this.orderHeaderData, orderHeaderData)
        },
        deleteOrder () {
            //删除
            let _this = this;
            let postData = {
                id: this.orderId
            };
            if (_this.orderId) {
                _this.$confirm({
                    title: "确认",
                    content: (
                        <span>
                            您确定要{<span style="color:red;">删除</span>}该条单据吗？
                        </span>
                    ),
                    onOk () {
                        _this.remove(postData);
                    },
                    onCancel () { },
                });
            }

        },
        clickEdit () {
            //修改 关闭遮罩层
            this.editMask = false;
        },
        printOrder () {
            //打印
            this.$print(this.$refs.print);
        },
        totalCalculate () {
            //合计计算
            let includeTaxAmountTotal = 0;  //含税金额总价
            let amountTotal = 0;            //金额总价
            let taxTotal = 0;                 //税额
            let baseQuantityTotal = 0;        //数量

            for (let i = 0; i < this.dataSource.length; i++) {
                if (this.dataSource[i].amount && this.dataSource[i].name != 'total') {
                    includeTaxAmountTotal += Number(this.dataSource[i].includeTaxAmount);
                    amountTotal += Number(this.dataSource[i].amount);
                    taxTotal += Number(this.dataSource[i].tax);
                    baseQuantityTotal += Number(this.dataSource[i].baseQuantity);
                }
                if (this.dataSource[i].name == 'total') {
                    this.dataSource[i].includeTaxAmount = includeTaxAmountTotal.toFixed(2);
                    this.dataSource[i].amount = amountTotal.toFixed(2);
                    this.dataSource[i].tax = taxTotal.toFixed(2);
                    this.dataSource[i].baseQuantityHide = baseQuantityTotal.toFixed(2);
                }
            }
            this.reload();
        },
        //=============================== 表头的搜索选择 ==========================

        //=============================== 右键（新增，删除，修改） ==========================
        openMenu (e) {
            console.log(e);
            //显示右键菜单
            var x = e.pageX - 250;
            var y = e.pageY - 40;
            this.top = y;
            this.left = x;
            this.visible = true;
        },
        closeMenu () {
            //隐藏右键菜单
            this.visible = false;
        },
        handleAdd () {
            //新增数据
            const { count, dataSource } = this;
            const newData = {
                number: count,
            };
            this.$nextTick(() => {
                this.dataSource.splice(this.dataSource.length - 1, 0, newData);
                // this.$refs.print.scrollTo(0, 500)
                // document.getElementsByClassName('documents-wrapper').scroll(0, 500)
                document.getElementById('documents-wrapper').scroll(0, this.$refs.print.scrollHeight)
                this.reload();
            })
        },
        handleDelete () {
            //删除整行
            let _this = this;
            let numberId = this.thisClickId;
            console.log(numberId);
            this.$confirm({
                title: "确认",
                content: (
                    <span>
                        您确定要{<span style="color:red;">删除</span>}该记录吗？
                    </span>
                ),
                onOk () {
                    let dataSource = [..._this.dataSource];
                    console.log(_this.dataSource.length);
                    if (dataSource.length - 1 > _this.dataSourceNumber) {
                        //大于规定行数(删除)
                        _this.dataSource = dataSource.filter((item, index) => index !== numberId);
                    } else {
                        //小于规定行数(清空)
                        for (let i = 0; i < dataSource.length; i++) {
                            if (i === numberId) {
                                for (const key in dataSource[i]) {
                                    if (key != 'number') {
                                        dataSource[i][key] = ""
                                    }
                                }
                            }
                        }
                        _this.dataSource = dataSource;
                    }


                    _this.reload();
                },
                onCancel () { },
            });
        },
        handleCopy () {
            //复制行
            const { count, dataSource, thisClickRecord } = this;
            console.log(thisClickRecord)
            if (!thisClickRecord.inventoryCode) {
                this.$message.warning('复制数据不存在！', 1)
                return;
            }
            // this.dataSource = [...dataSource, newData];
            let nowData = { ...thisClickRecord };
            // nowData.number = count;
            nowData.id = '';
            newData.orderId = '';
            newData.sourceVoucherCode = '';
            newData.sourceVoucherDate = '';
            newData.sourceVoucherId = '';
            newData.sourceVoucherType = '';

            this.dataSource.splice(this.thisClickId + 1, 0, nowData);
            this.reload();
        },
        choiceAddData (index, record) {
            //物料多选
            let newData = [...record];
            let runAddDataSource = true;
            console.log(newData, this.dataSource)

            //判断列表中是否存在该物料
            // for (let i = 0; i < newData.length; i++) {
            //     for (let k = 0; k < this.dataSource.length; k++) {
            //         if (this.dataSource[k].inventoryId == (newData[i].inventoryId || newData[i].id)) {
            //             this.$message.error('物料已经存在当前单据,不能重复添加', 1);
            //             runAddDataSource = false;
            //             break;
            //         }
            //     }
            // }
            if (runAddDataSource) {
                for (let i = 0; i < newData.length; i++) {
                    let newDetails = {};
                    newDetails['inventoryCode'] = newData[i].inventoryCode;//物料编码
                    newDetails['inventoryId'] = newData[i].id;//物料名称
                    newDetails['inventoryName'] = newData[i].inventoryName;//物料名称
                    newDetails['inventorySpecification'] = newData[i].inventorySpecification;//规格型号
                    newDetails['taxRate'] = newData[i].taxRate ? newData[i].taxRate : 13;//税率

                    //处理库存初期，仓库
                    this.orderHeaderData.forEach(element => {
                        if (element.code == 'warehouseId') {
                            newDetails['warehouseId'] = element.valueId;
                            newDetails['warehouseName'] = element.valueName;
                        }
                    });


                    if (newData[i].unitType == '单计量') {
                        newDetails['baseUnit'] = newData[i].unitName;//单计量
                        newDetails['baseUnitName'] = newData[i].unitName;//单计量
                        newDetails['baseUnit_temp_id'] = newData[i].unitId;//单计量id
                        newDetails['unitId'] = newData[i].unitId;//单计量id
                    } else {
                        let mainId = null;//主计量id
                        for (let j = 0; j < this.unitsDataDetails.length; j++) {
                            if (this.unitsDataDetails[j].id == newData[i].mainUnit) {
                                newDetails['baseUnit'] = this.unitsDataDetails[j].name;//主计量
                                newDetails['baseUnitName'] = this.unitsDataDetails[j].name;//主计量
                                newDetails['baseUnit_temp_id'] = this.unitsDataDetails[j].id;//主计量id
                                newDetails['baseUnitId'] = this.unitsDataDetails[j].id;
                                newDetails['unitGroupId'] = this.unitsDataDetails[j].id;
                                mainId = this.unitsDataDetails[j].unitGroupId;
                            }
                        }

                        //辅助计量数据
                        let unitsAssistSelect = [];
                        this.unitsDataDetails.forEach(element => {
                            if (element.unitGroupId == mainId && !element.isMainUnit) {
                                unitsAssistSelect.push(element);
                            }
                        });
                        newDetails['subUnit'] = unitsAssistSelect[0].name;
                        newDetails['subUnit_temp_id'] = unitsAssistSelect[0].id;
                        newDetails['unitExchangeRate'] = unitsAssistSelect[0].changeRate;  //换算率
                    }

                    this.dataSource.splice(index + i, 0, newDetails);

                }
            }
            this.reload();
        },
        //=============================== 右键（新增，删除，修改） ==========================



        //=============================== 翻页 ==========================
        turnThePage (turnpage) {
            this.loading = true;
            let defaultPageData = {
                currentId: this.orderId,
                source: this.sourceCode,
                actionType: turnpage,//1:上一页 2：下一页 3：首页 4：尾页
                businessType: this.businessType
            }
            getbyid(defaultPageData).then((response) => {
                if (response.code === 200) {
                    const backData = response.data;
                    if (backData) {
                        if (!backData.voucherState) {
                            this.$set(backData, 'voucherState', 0)
                        }
                        this.editMask = true;   //开启遮罩
                        this.orderId = backData.id;
                        this.initForm(2);
                        setTimeout(() => {
                            this.editClickOrder(backData);
                            //判断如果是加工单（获取加工单下的物料明细和工序明细）
                            // if (this.sourceCode == 'ProductionWork') {
                            //     //加工单
                            //     this.getSaveDetails(backData);
                            // }
                        }, 300)
                    } else {
                        if (turnpage == 1 || turnpage == 3) {
                            this.loading = false;
                            this.$message.destroy();
                            this.$message.warning('已经是首页了');
                        } else {
                            this.loading = false;
                            this.$message.destroy();
                            this.$message.warning('已经是尾页了');
                        }
                        setTimeout(() => {
                            this.$message.destroy();
                        }, 1000)
                    }
                } else {
                    // this.$message.warning(res.message);
                }
            })
        },
        //=============================== 翻页 ==========================



        //获取最新一条数据
        getIdByData () {
            this.editMask = true;   //开启遮罩
            let defaultPageData = {
                currentId: this.orderId,
                source: this.sourceCode,
                businessType: this.businessType
            }
            console.log('生单数组长度' + Object.keys(this.invoiceData).length)
            if (Object.keys(this.invoiceData).length > 0) {
                this.initForm(2);
                setTimeout(() => {
                    // this.getCode();
                    this.editClickOrder(this.invoiceData, 'iscreate');
                }, 300)
            } else {
                this.loading = true;
                getbyid(defaultPageData).then((response) => {
                    if (response.code === 200) {

                        const backData = response.data;
                        if (defaultPageData.currentId == '' && !backData) {
                            //表示一条数据都没有 去新增
                            this.newForecast();
                        } else {
                            if (backData) {
                                this.orderId = backData.id;
                                if (!backData.voucherState) {
                                    this.$set(backData, 'voucherState', 0)
                                }
                                this.initForm(2);
                                setTimeout(() => {
                                    if (Object.keys(this.invoiceData).length == 0) {
                                        this.editClickOrder(backData)

                                        //判断如果是加工单（获取加工单下的物料明细和工序明细）
                                        // if (this.sourceCode == 'ProductionWork') {
                                        //     //加工单
                                        //     this.getSaveDetails(backData);
                                        // }
                                    }
                                }, 300)
                            }
                        }

                    } else {
                        // this.$message.warning(res.message);
                    }
                })
            }

        },




        //去除数据中的id
        copyRemoveIdData (data) {
            let backData = JSON.parse(data);
            let details = backData.detailList;
            backData.id = '';
            backData.voucherState = 0;
            for (const key in details) {
                details[key].id = '';
                details[key].orderId = '';
            }
            return backData;
        },




        //=============================== 选单 ==========================
        choiceBills (source, ischoose, title, businessType) {
            /**
             * source: 单据类型(来源单据source)
             * ischoose：是否是选单
             * title:抽屉名
             * voucherState==1审核通过，才能选单
             */
            this.$refs.searchList.onOpen(source, ischoose, title, 1, businessType);
        },
        //=============================== 选单 ==========================



        //=============================== 生单 ==========================
        generateBills (source) {
            //储存当前页数据(去除id)
            let defaultPageData = {
                currentId: this.orderId,
                source: this.sourceCode,
            }
            getbyid(defaultPageData).then((response) => {
                if (response.code === 200) {
                    const backData = response.data;


                    this.$set(backData, 'generateSourceCode', source);

                    this.$set(backData, 'sourceVoucherId', backData.id);    //来源id
                    this.$set(backData, 'sourceVoucherCode', backData.voucherCode);    //来源单号
                    this.$set(backData, 'sourceVoucherDate', backData.voucherDate);    //来源日期
                    this.$set(backData, 'sourceVoucherType', this.sourceCode);   //来源单据

                    //明细中添加来源
                    backData.detailList.forEach(element => {
                        this.$set(element, 'sourceVoucherId', backData.id);    //来源id
                        // this.$set(element, 'sourceVoucherId', element.id);    //来源id
                        this.$set(element, 'sourceVoucherCode', backData.voucherCode);    //来源单号
                        this.$set(element, 'sourceVoucherDate', backData.voucherDate);    //来源日期
                        this.$set(element, 'sourceVoucherType', this.sourceCode);   //来源单据


                    });

                    //退货单特殊处理
                    if (source == 1) {
                        backData.businessType = 99;
                    } else if (source == 2) {
                        //销售退货单
                        backData.businessType = 98;
                    }

                    //数量的处理
                    backData.detailList.forEach(element => {
                        

                        if (backData.businessType == 99 || backData.businessType == 98) {
                            //退货
                            element.baseQuantity = Math.abs(element.baseQuantity) - (element.cumRetQuantity ? element.cumRetQuantity : 0);
                        } else {
                            //其他
                            element.baseQuantity = Math.abs(element.baseQuantity) - (element.cumExecuteQuantity ? element.cumExecuteQuantity : 0);
                        }
                        element.orgBaseQuantity = element.baseQuantity;
                    });

                    //如果数量为0,则删除该条数据
                    // let generateData = [];
                    // backData.detailList.forEach(element => {
                    //     if(element.baseQuantity != 0){
                    //         generateData.push(element)
                    //     }
                    // });

                    backData.detailList = backData.detailList.filter(item => item.baseQuantity != 0);

                    console.log('生单的详情数据', backData);

                    this.$store.commit('SET_ARR', backData)
                    // 如果$store.state.order.invoiceData有数据，才能生单
                    if (this.invoiceData) {
                        switch (source) {
                            case 'PurchaseOrder':
                                //采购订单
                                this.$router.push({ path: '/procurement/purchaseOrder' })
                                break;
                            case 'PuArrival':
                                //采购到货单
                                this.$router.push({ path: '/procurement/purchaseReceipt' })
                                break;
                            case 1:
                                //采购退货单
                                this.$router.push({ path: '/procurement/purchaseReturn' })
                                break;
                            case 'PurchaseInvoice':
                                //采购发票
                                this.$router.push({ path: '/procurement/purchaseInvoice' })
                                break;
                            case 'SaleQuotation':
                                //报价单
                                this.$router.push({ path: '/sale/saleQuotation' })
                                break;
                            case 'SaleOrder':
                                //销售订单
                                this.$router.push({ path: '/sale/saleOrder' })
                                break;
                            case 'SaleDelivery':
                                //销售发货单
                                this.$router.push({ path: '/sale/saleDelivery' })
                                break;
                            case 2:
                                //销售退货单
                                this.$router.push({ path: '/sale/saleReturn' })
                                break;
                            case 'SaleInvoice':
                                //销售发票
                                this.$router.push({ path: '/sale/saleInvoice' })
                                break;
                            case 'PurchaseReceiveVoucher':
                                //采购到货 -> 采购入库单
                                this.$refs.purchaseInRef.purchaseShowModel(1);
                                break;
                            case 'PurchaseReturn':
                                //采购退货 -> 采购入库单
                                this.$refs.purchaseInRef.purchaseShowModel(2);
                                break;
                            case 'ProductReceiveVoucher':
                                //产成品入库单 || 完工入库单
                                this.$refs.productionInRef.purchaseShowModel(1);
                                break;
                            case 'DelegateReceiveVoucher':
                                //委外入库
                                this.$router.push({ path: '/inventory/bills/delegateIn' })
                                break;
                            case 'OtherReceiveVoucher':
                                //其他入库单
                                this.$router.push({ path: '/inventory/bills/otherIn' })
                                break;
                            case 'SaleDispatchVoucher':
                                //销售出库单
                                // this.$router.push({ path: '/inventory/bills/saleOut' })
                                this.$router.push({ path: '/sale/saleOut' })
                                break;
                            case 'MaterialDispatchVoucher':
                                //材料出库单
                                this.$router.push({ path: '/inventory/bills/materialOut' })
                                break;
                            case 'DelegateDispatchVoucher':
                                //委外发料
                                this.$router.push({ path: '/inventory/bills/delegateOut' })
                                break;
                            case 'OtherDispatchVoucher':
                                //其他出库单
                                this.$router.push({ path: '/inventory/bills/otherOut' })
                                break;
                            case 'ProductionWork':
                                //加工单
                                this.$router.push({ path: '/production/productionWork' })
                                break;
                            default:
                                this.$message.error('生单失败');
                                break;
                        }
                    }



                } else {
                    // this.$message.warning(res.message);
                }
            })


        },
        //=============================== 生单 ==========================



        /**
        * 处理动态表单数据
        * @example handleDynamicData('请求参数')
        */
        handleDynamicData (code) {
            listDesign({ source: code }).then((response) => {
                if (response.code === 200) {
                    const { data } = response;

                    //给动态表名新增value字段（用于提交数据）
                    for (let i = 0; i < data.length; i++) {
                        const element = data[i];
                        element.value = '';
                        element.valueId = '';
                        element.valueName = '';
                    }
                    this.dynamicFormData = data.filter(item => item.onOff == true);  //返回的详细数据
                } else {
                    // this.$message.warning(res.message);
                }
            })
        },
        //重组表格columns
        regroupTableColumns (data) {
            let tableColumns = [];
            data.unshift({
                name: '序号',
                code: 'number',
                key: 'number',
                columnWidth: 40,
                // fixed: 'left',
                align: 'center',
            })



            if (data && typeof data == 'object') {
                //采购管理（采购入库单）隐藏仓库和仓库编码
                if (this.isHideWherehouse) {
                    // data = data.filter(item => item.code != 'warehouseName')
                    // data = data.filter(item => item.code != 'warehouseCode')inventoryName
                    data = data.filter(item => item.code != 'warehouseCode')
                    data = data.filter(item => item.name != '仓库')
                }

                //采购到货，采购退货  隐藏明细中的客户
                if (this.isDetailCrmId) {
                    data = data.filter(item => item.code != 'crmId')
                }

                console.log('明细', data)
                for (let i = 0; i < data.length; i++) {
                    if (data[i].columnType == '搜索选择') {
                        data[i].code = IdFieldToNameField(data[i].code)
                    }
                    let title = data[i].name;
                    if (data[i].onFill) {
                        title = <div><span style="color:red;font-family: SimSun,sans-serif;font-size:14px">*</span> {data[i].name}</div>
                    }




                    let columns = {
                        title: title,
                        key: data[i].code,
                        dataIndex: data[i].code,
                        scopedSlots: { customRender: data[i].code },
                        width: data[i].columnWidth,
                        fixed: data[i].fixed,
                        align: data[i].align,
                        ellipsis: true,
                    }


                    tableColumns.push(columns)
                }
            } else {
                this.$message.error('error');
                return;
            }
            return tableColumns;
        },
        /**
         * 组装提交数据
         * data:{
         *  detail:明细
         *  header:表头
         *  footer:表尾
         *  customField：自定义字段
         *  /^(\d+[a-zA-Z]+|[a-zA-Z]+\d+)([0-9a-zA-Z]*)$/ 包含数字或者字母的code，就是自定义数据
         * }
         */
        submitRegData (data) {
            let commitData = {
                orderDetailList: [],//请购单明细
                defineFields: '',//自定义字段
            };

            //保存要提交的合计字段
            console.log(data.detail);
            data.detail.forEach(item => {
                if (item.name == 'total') {
                    commitData.totalQuantity = item.baseQuantityHide;//数量
                    commitData.totalAmount = item.amount;//金额
                    commitData.totalTaxAmount = item.tax;//税额
                    commitData.totalIncludeTaxAmount = item.includeTaxAmount;//含税金额
                }
            });


            let m = data.detail.slice(0, -1);//删除合计列

            let reg = /^(\d+[a-zA-Z]+|[a-zA-Z]+\d+)([0-9a-zA-Z]*)$/;//（自定义字段）必须包含字母和数字


            let s = [];//传给后台的明细表数据
            for (let i = 0; i < m.length; i++) {
                if (m[i].inventoryId || m[i].inventoryName) {//有物料id或者物料名字的才传给后台
                    s.push(m[i])
                }
            }

            //明细表自定义数据
            for (const key in s) {
                let cust = {};
                for (const k in s[key]) {
                    if (reg.test(k)) {
                        let a = {};
                        a[k] = s[key][k];
                        console.log(a);
                        Object.assign(cust, a)
                    }
                }
                s[key].defineFields = JSON.stringify(cust);
            }

            commitData.orderDetailList = Object.assign([], s);

            commitData.defineFields = JSON.stringify(this.regroupSubmitData(data.customField));

            return commitData = Object.assign(
                commitData,
                this.regroupSubmitData(data.header),
                this.regroupSubmitData(data.footer)
            )
        },
        //提交数据时 获取数据的value值
        regroupSubmitData (data) {
            let m = {};
            for (const key in data) {
                //不可修改的也需要传值给后台的处理
                if (data[key].onEdit === true || data[key].code == 'businessType' || data[key].code == 'purchaseTypeCode' || data[key].code == 'warehouseCode') {
                    if (data[key].valueId) {
                        //如果valueId存在，说明要提交的是选中的id
                        m[data[key].code] = data[key].valueId;
                    } else {
                        m[data[key].code] = data[key].value;
                    }
                }
            }
            return m;
        },
        //判断是否是数组
        isArray (obj) {
            return Object.prototype.toString.call(obj) === '[object Array]';
        },
        //是否是对象
        isObject (obj) {
            return Object.prototype.toString.call(obj) === '[object Object]';
        },
        deepCopy (target) {
            // 定义一个变量
            let result;
            //如果当前需要深拷贝的是一个对象的话
            if (typeof target === 'object') {
                //如果是一个数组的话
                if (Array.isArray(target)) {
                    result = []; // 将result赋值为一个数组，并且执行遍历
                    for (let i in target) {
                        //递归克隆数组中的每一项
                        result.push(this.deepCopy(target[i]));
                    }
                    // 判断如果当前的值是null的话；直接赋值为null
                } else if (target === null) {
                    result = null;
                    // 判断如果当前的值是一个RegExp对象的话，直接赋值    
                } else if (target.constructor === RegExp) {
                    result = target;
                } else {
                    // 否则是普通对象，直接for in循环，递归赋值对象的所有值
                    result = {};
                    for (let i in target) {
                        result[i] = this.deepCopy(target[i]);
                    }
                }
                // 如果不是对象的话，就是基本数据类型，那么直接赋值
            } else {
                result = target;
            }
            // 返回最终结果
            return result;
        },
        //下拉选择赋值处理
        handleDownChoice (id, val) {
            let label = '';
            val = JSON.parse(val);
            val.forEach(element => {
                if (id == element.key) {
                    label = element.label;
                }
            });
            return label;
        },
        //处理下拉选择（退货单情况）
        formatSelectJsonVal (val) {
            let thisVal = JSON.parse(val);
            let backVal = [];
            if (thisVal && thisVal != '' && thisVal != null) {
                thisVal.forEach((item, index) => {
                    //采购退货||销售退货 （因为页面单独分出来，单独判断）
                    if (this.businessType) {
                        if ((item.key == 99 || item.key == 98 || item.key == 97 || item.key == 96) && this.businessType == 1) {
                            backVal.push(item);
                        }
                        if (item.key != 99 && item.key != 98 && item.key != 97 && item.key != 96 && this.businessType != 1) {
                            backVal.push(item);
                        }
                    } else {
                        //其他单据处理   业务类型
                        backVal.push(item);
                    }

                });
            }
            return backVal;
        },
        //列表和单据切换
        switchList (type) {
            this.showModel = type;
            if (type == 'list') {
                //列表
                // this.$refs.dyList.searchList();
                this.$refs.dyList.getMyselfPlan();
            } else if (type == 'detail') {
                //明细
                this.$refs.detailSearchRef.getSystemplan();
                this.$refs.detailSearchRef.getMyselfPlan();
                this.$refs.detailSearchRef.getUnit();
            } else if (type == 'statistical'); {
                //统计
                this.$refs.statisticalSearchRef.getSystemplan();
                this.$refs.statisticalSearchRef.getMyselfPlan();
                this.$refs.statisticalSearchRef.getUnit();
            }
        }
    },
}

/**
 * 单据请求code汇总：
 */

// PurchaseRequisition	请购单
// PurchaseOrder	    采购订单
// PuArrival	        到货单
// PurchaseInvoice	    采购发票


// SaleQuotation	    报价单
// SaleOrder	        销售订单
// SaleDelivery	        销售发货单
// SaleInvoice	        销售发票


// PurchaseReceiveVoucher	采购入库单
// ProductReceiveVoucher	产成品入库单
// DelegateReceiveVoucher   委外入库
// OtherReceiveVoucher	    其他入库单


// SaleDispatchVoucher	    销售出库单
// MaterialDispatchVoucher	材料出库单
// DelegateDispatchVoucher  委外发料
// OtherDispatchVoucher	    其他出库单
// StockRequestVoucher	    领料单


// ArapReceiveVoucher	收款单
// ArapPaymentVoucher	付款单
// ArapStrikeBalanceAdvReceiveAr	预收冲应收
// ArapStrikeBalanceAdvPaymentAp	预付冲应付
// ArapStrikeBalanceArAr	应收冲应收
// ArapStrikeBalanceApAp	应付冲应付
// ArapStrikeBalanceArAp	应收冲应付
// ArapExchangeAdjust	    汇兑损益调整单
// bankCashAccessVoucher	银行存取款单
// expenseVoucher	费用单
// incomeVoucher	收入单
// OtherPaymentVoucher	    其他应付单
// OtherReceiveCSVoucher	其他应收单
// CashCheckVoucher	        现金盘点单
// GLDoc	凭证
// OutSourceExpenseVoucher	委外费用单
// OutSourceOrder	        委外加工单
// PraVoucher	            采购需求分析
// PurchaseArrivalPeriodStart	期初进货单
// CostAllocationOrder	    产品成本分配单
// AdjustCostInVoucher	    入库调整单
// AdjustCostOutVoucher	出库调整单
// TransVoucher	调拨单
// CheckVoucher	盘点单
// ShareExpenseVoucher	        费用分摊单
// PurchaseSettleVoucher	    采购核算单
// PSPurchaseReceiveVoucher	    期初暂估入库单
// PSSaleDispatchVoucher	    期初销售出库单
// RedBackVoucher	    红字回冲单
// BlueBackVoucher	    蓝字回冲单
